package dev.ideas.funkyj.group;

import java.util.Iterator;

/**
*/
//todo what about concurrency?
class CachedSequence<T> extends _Group.Leaf<T> implements Iterable<T> {
    CachedSequence(_Group.Root<T> root) { super(root); }

    /*@Override*/ public Iterator<T> iterator() {
        return new Iterator<T>() {
            int cursor = 0; //reset cursor on new iterator

            public boolean hasNext() {
                while (!(cursor < cache.size())) {
                    if (root.hasNext()) {
                        root.next();
                    } else {
                        return false;
                    }
                }
                return true;
            }
            public synchronized T next() { return cache.get(cursor++); }
            public void remove() { throw new UnsupportedOperationException(); }
        };
    }
}
